import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/home/news_match_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/utils/widget_utils.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

// const _black = Colors.black;

// const _stat1 = "加时";
// const _stat2 = "点球";
// const _stat3 = "比赛推迟";
// const _stat7 = "延期";
// const _red = Color(0xFFF53F3F);

// const _stat4 = "中断";
// const _orange = Color(0xFFFF7D00);

// const _stat5 = "取消";
// const _stat6 = "腰斩";
// const _grey66 = Color(0xff666666);

// const _stat8 = "时间";
// const _grey99 = Color(0xff999999);

class NewsMatchView extends StatefulWidget {
  const NewsMatchView({super.key, required this.matches, this.click});

  final List<NewsMatchEntity> matches;
  final void Function(NewsMatchEntity)? click;

  @override
  State<NewsMatchView> createState() => _NewsMatchViewState();
}

class _NewsMatchViewState extends State<NewsMatchView> {
  final scrollC = ApmScrollController();
  List<NewsMatchEntity> get matches => widget.matches;
  int _lastIndex = 0;

  Map<DateTime, List<NewsMatchEntity>> mapOfMatches = {};
  DateTime? date;

  init() {
    mapOfMatches = {};
    for (var i = 0; i < matches.length; i++) {
      final match = matches[i];
      final date = match.getMatchDate?.nextStartDay(0);
      if (date == null) {
        continue;
      }
      if (this.date == null) {
        this.date = date;
      }
      List<NewsMatchEntity> l = mapOfMatches[date] ?? [];
      l.add(match);
      mapOfMatches[date] = l;
    }
  }

  @override
  void initState() {
    super.initState();

    init();

    scrollC.addListener(() {
      final index = (scrollC.offset / 180).floor();
      if (index < 0 || index >= matches.length) {
        return;
      }
      if (index == _lastIndex) {
        return;
      }
      _lastIndex = index;
      date = matches[index].getMatchDate?.nextStartDay(0);
      update();
    });
  }

  @override
  void dispose() {
    scrollC.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant NewsMatchView oldWidget) {
    init();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // matches = matches.sublist(0,2);
    // final num = matches.length;
    return LayoutBuilder(
      builder: (p0, p1) {
        // double width = 170;
        // if (num > 2) {
        //   width = (p1.maxWidth - 30 - 32) / 2;
        // } else if (num == 2) {
        //   width = (p1.maxWidth - 10 - 32) / 2;
        // }

        return DefaultTextStyle(
            style: const TextStyle(fontSize: 12, color: Colors.black),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            child: SizedBox(
              height: matches.isEmpty ? 0 : 98,
              child: Row(
                children: [
                  Expanded(
                    child: Stack(
                      children: [
                        if (matches.length == 1) singleMatch(matches.first),
                        if (matches.length > 1)
                          ListView.builder(
                            physics: const ClampingScrollPhysics(),
                            controller: scrollC,
                            itemCount: matches.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: (context, idx) {
                              final index = idx;
                              final isLast = (index == matches.length - 1);
                              final isFirst = index == 0;
                              final e = matches[index];
                              return GestureDetector(
                                onTap: () {
                                  Utils.onEvent('toutiao_match',
                                      params: {'id': matches[index].id});
                                  // Get.find<UmService>().payOriginRoute = 'rmbs${index + 1}';
                                  widget.click?.call(e);
                                },
                                child: Padding(
                                  padding: EdgeInsets.only(
                                      left: isFirst ? 8 : 0,
                                      right: isLast ? 8 : 8),
                                  child: _card(e, 170),
                                ),
                              );
                            },
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ));
      },
    );
  }

  Widget singleTeam(String img, String name, String rank) => Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              margin: const EdgeInsets.only(bottom: 8),
              width: 40,
              height: 40,
              child: CachedNetworkImage(imageUrl: img),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                QsText(name, fontSize: 15),
                if (rank.isNotEmpty)
                  QsText("[$rank]", color: Colours.grey99, fontSize: 10)
              ],
            )
          ],
        ),
      );

  Widget singleMidStatus(NewsMatchEntity match, bool isPlaying) => Container(
        width: 140,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            QsText(match.leagueName ?? "", color: Colours.grey99, fontSize: 12),
            const SizedBox(
              height: 8,
            ),
            if (!isPlaying) QsText(match.getMatchDateDesc ?? "", fontSize: 18),
            if (isPlaying)
              QsText(
                "${match.homeScore} : ${match.guestScore}",
                fontWeight: FontWeight.w500,
                fontSize: 18,
              ),
            const SizedBox(
              height: 8,
            ),
            if (!isPlaying) QsText("未开赛", color: Colours.grey99, fontSize: 12),
            if (isPlaying)
              Row(
                // crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  QsText("${match.matchTime}",
                      color: Colours.main, fontSize: 12),
                  const SizedBox(width: 4),
                  Image.asset(Utils.getImgPath("icon_match_playing.png"),
                      width: 10, height: 10)
                ],
              )
          ],
        ),
      );

  Widget singleMatch(NewsMatchEntity match) => Container(
        margin: const EdgeInsets.symmetric(horizontal: 8),
        padding: const EdgeInsets.symmetric(horizontal: 20),
        decoration: BoxDecoration(
            color: Colours.white,
            border: Border.all(color: Colours.main.withOpacity(0.1), width: 1),
            borderRadius: BorderRadius.circular(8)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: singleTeam(match.homeLogo ?? "", match.homeName ?? "",
                  match.homeRanking ?? ""),
            ),
            singleMidStatus(match, match.matchTime?.contains("'") ?? false),
            Expanded(
              child: singleTeam(match.guestLogo ?? "", match.guestName ?? "",
                  match.guestRanking ?? ""),
            ),
          ],
        ),
      ).tap(() {
        Get.toNamed(Routes.zqMatchDetail, arguments: match.id);
      });

  _card(NewsMatchEntity e, double width) {
    bool isPlay = e.matchTime?.contains("'") ?? false;
    return SizedBox(
      width: width,
      child: Container(
        // padding: const EdgeInsets.all(10),
        // margin: const EdgeInsets.symmetric(vertical:5),
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colours.main.withOpacity(0.1), width: 1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              color: Colours.main.withOpacity(0.1),
              height: 26,
              child: Row(
                children: [
                  Expanded(
                    child: QsText(
                        "${e.matchNo.hasValue == false ? '' : ('${e.matchNo!} ')}${e.leagueName}",
                        fontSize: 11),
                  ),
                  SizedBox(
                    width: 64,
                    child: Row(
                      children: [
                        QsText(
                          "${e.matchTime}",
                          textAlign: TextAlign.right,
                          fontSize: 11,
                          color: isPlay ? Colours.main : Colours.grey66,
                        ),
                        if (e.status == 2 || e.status == 4)
                          const QsText("'")
                              .animate(
                                onPlay: (controller) => controller.repeat(),
                              )
                              .fade(duration: 1000.ms)
                      ],
                    ),
                  ),
                  if (isPlay)
                    Image.asset(Utils.getImgPath("icon_match_playing.png"),
                            width: 10, height: 10)
                        .marginOnly(left: 4)
                  // TimeShowWidget(
                  //     time: DateTime.now().add(Duration(seconds: seconds))),
                ],
              ),
            ),
            const SizedBox(height: 10),
            _teamWidget(
                e.homeLogo, e.homeName, e.homeRanking, e.homeScore, width),
            const SizedBox(height: 8),
            _teamWidget(
                e.guestLogo, e.guestName, e.guestRanking, e.guestScore, width),
            // const SizedBox(height: 10),
            const Spacer(),
            const Divider(
              height: 0.5,
              color: Colours.greyEE,
            ),
          ],
        ),
      ),
    );
  }

  Widget _teamWidget(String? icon, String? name, String? rank, String? score,
      double maxWidth) {
    const iconsize = 22.0;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      height: iconsize,
      child: Row(
        children: [
          Container(
            decoration: const BoxDecoration(shape: BoxShape.circle),
            child: CachedNetworkImage(
              imageUrl: icon ?? "",
              errorWidget: (context, error, stackTrace) => Image.asset(
                Utils.getImgPath('zq_placeholder.png'),
                width: iconsize,
                height: iconsize,
              ),
              placeholder: (context, child) => Styles.placeholderIcon(),
              width: iconsize,
              height: iconsize,
            ),
          ),
          const SizedBox(width: 8),
          Container(
              constraints: BoxConstraints(maxWidth: maxWidth - 80),
              child: QsText("$name")),
          const SizedBox(width: 4),
          rank?.isEmpty ?? true
              ? Container()
              : QsText("[$rank]", fontSize: 10, color: Colours.grey66),
          const Spacer(),
          QsText(score ?? "-",
              fontSize: 11, color: Colours.text, fontWeight: FontWeight.w600)
        ],
      ),
    );
  }
}
